<?php
function dirList ($directory) 
{
    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);
    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {

        // if $file isn't this directory or its parent, 
        // add it to the results array
        if ($file != '.' && $file != '..')
            $results[] = "../auctions/".$file;
    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;

}

function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //vars
    $valid_files = array();
    //if files were passed in...
    if(is_array($files)) {
        //cycle through each file
        foreach($files as $file) {
            //make sure the file exists
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //if we have good files...
    if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $zip->addFile($file,$file);
        }
        //debug
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
         
        //close the zip -- done!
        $zip->close();
         
        //check to make sure the file exists
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}

#
function folderDelete($path) {
#
if (is_dir($path)) {
#
if (version_compare(PHP_VERSION, '5.0.0') < 0) {
#
$entries = array();
#
if ($handle = opendir($path)) {
#
while (false !== ($file = readdir($handle))) $entries[] = $file;
#
closedir($handle);
#
}
#
}else{
#
$entries = scandir($path);
#
if ($entries === false) $entries = array();
#
}
#
 
#
foreach ($entries as $entry) {
#
if ($entry != '.' && $entry != '..') {
#
folderDelete($path.'/'.$entry);
#
}
#
}
#
 
#
//return rmdir($path);
#
}else{
#
return unlink($path);
#
}
#
}

/**
 * Enter description here...
 *
 * @param unknown_type $sDateTime
 * @return unknown
 */
 function getDateFromDateTime( $sDateTime = '0000-00-00 00:00:00' ){
	return substr($sDateTime, 0, 10);	
}
/**
 * Enter description here...
 *
 * @param unknown_type $sDateTime
 * @return unknown
 */
function getTimeFromDateTime( $sDateTime = '0000-00-00 00:00:00' ){
	return substr($sDateTime, 11, 8);	
}
/**
 * function getAVG
 * 
 * @param $total, $times
 * 
 * @return $avg
 */
function getAVG( $total, $times ){
	return $avg = $total / $times;
}
/**
 * getLastCashed()
 *
 * @param date $checkDateTime
 * @return int $iDay
 */
 
function getTotalDays( $checkDateTime ){
	$checkDate = strtotime( getDateFromDateTime( $checkDateTime ) );
	$iDay = floor( ( time() - $checkDate) / 86400 );
	return $iDay;
}
function getTotalYears( $totalDays ){
	$iYears = $totalDays / 365;
	return floor( $iYears );
}
function getTotalMonths( $totalDays ){
	$modDay = $totalDays % 365;
	$iMonth = $modDay / 30; 
	return floor( $iMonth );
}


/*
Date: 26/09/2008
Written by : Nguyen Thanh Dung
Function name: CompareDate
Purpose: Compare old date with date now
  - Input: Receive a date value 
  - Ouput: return a message with any format 
  For instance results: Today, Yesterday, 3 Months 2 days, 2 Years 3 months 2 days
*/
function CompareDate($checkDateTime) {	
    $time =  substr($checkDateTime, 0, 10);
	$checkDate = strtotime($time);
	$iDay = floor( ( time() - $checkDate) / 86400 );
	$isYear = $iDay/360;
	$year = $iDay/360;
	$month = ($iDay%360);
	$stringYear = '';
	$stringMonth = '';
	$stringDay = '';
	if($iDay >= 360) {
	    $years = floor($iDay/360);
		$surplusday = $iDay%360;
		$month = floor($surplusday/30);
		$surplusmonth = $surplusday%30;
		$day = $surplusmonth;
			if($years == 1) {
				$stringYear .= " year";
			}elseif ($years==0){
				$stringYear .= "";
				$years='';
					}else {
						$stringYear .= " years";
					}
			if($month == 1) {
				$stringMonth = ' month';	
			}elseif ($month==0)
					{
					$month='';	
					$stringMonth = '';
					}else {
						$stringMonth = ' months';
						}
			if($day == 1) {
				$stringDay = ' day';	
			}elseif ($day==0)
			{
				$stringDay='';
				$day='';
					}else {
							$stringDay = ' days';
						}
		if($surplusday == 0) {
			return $years.$stringYear;
		}
		if($surplusday != 0 && $surplusmonth == 0) {
			return $years.$stringYear.$month.$stringMonth;
		}
		if($surplusday != 0 && $surplusmonth != 0) {
			if ($month=='' || $month == 0)
			return $years.$stringYear." ";
			else 
			return $years.$stringYear.", ".$month.$stringMonth;
		}
		
	}
	if($iDay < 360 ) {
		$month = floor(($iDay*12)/360);
		$day = (($iDay*12)%360)*30/360;	
        if($month == 1) {  		
			$stringMonth = " month";
		}	
		else {
			$stringMonth = " months";
		}
		if($day == 1) {
				$stringDay = ' day';	
			}
			else {
				$stringDay = ' days';
			}
		if($month >= 1 ) {
		    if($day == 0) {
				return $month.$stringMonth;
			}
			if($day > 0 && $day !='' ) {
				return $month.$stringMonth.", ".$day.$stringDay;
			}
		}
		if($month < 1  ) {
		 
			if($day != 1 && $day != 0) {
				return $day." days";
			}
			if($day == 0 ) {
				return "Today";
			}
			if($day == 1) {
				return "Yesterday";
			}
		}
	}

}
/*---------------------------------------------------------*/
function redir($url){
	die(header("location: ".$url));
}

function redirIfnotLogin()
{
	$isLogin = false;
	
	if ((isset($_SESSION['admin_id'])) && ($_SESSION['admin_id'] != ''))
	{
		if ($_SESSION['type'] == 'Administrator')
		{
			$isLogin = true;
		}
	}
	
	if ((isset($_SESSION['casher_id'])) && ($_SESSION['casher_id'] != ''))
	{
		if ($_SESSION['type'] == 'Cashier')
		{
			$isLogin = true;
		}
	}
	
	if ($isLogin == false)
	{
		redir(URL_SITE."home");
	}
}
function randomPassword(){
	$sPassword = "";
	$iPasswordLen = 8;
	for($i=1; $i<=$iPasswordLen; $i++){
		$sPassword .= rand(0,9);
	}
	return $sPassword;
}

function preview_text($text, $limit=0, $tags = 0) {
	//$limit=CUTSTRING;
    // TRIM TEXT
    $text = trim($text);

    // STRIP TAGS IF PREVIEW IS WITHOUT HTML
    if ($tags == 0) $text = preg_replace('/\s\s+/', ' ', strip_tags($text));

    // IF STRLEN IS SMALLER THAN LIMIT RETURN
    if (strlen($text) < $limit) return $text;

    if ($tags == 0) return substr($text, 0, $limit) . "...";
    else {

        $counter = 0;
        for ($i = 0; $i<= strlen($text); $i++) {

            if ($text{$i} == "<") $STOP = 1;

            if ($STOP != 1) {

                $counter++;
            }

            if ($text{$i} == ">") $STOP = 0;
            $sTextReturn .= $text{$i};

            if ($counter >= $limit && $text{$i} == " ") break;

        }

        return $sTextReturn . "...";
    }

}

function getFileExt($filename){
	return strtolower(substr($filename,strrpos($filename,'.')+1));
}

function redirParent($url){
	echo '<script language="javascript">opener.location.href ="'.$url.'"; self.close();</script>';
}
function removeSharp($color){
	return str_replace('#','',$color);
}
function getColorR($color){
	return hexdec(substr($color,0,2));
}
function getColorG($color){
	return hexdec(substr($color,2,2));
}
function getColorB($color){
	return hexdec(substr($color,4,2));
}

function getMsg($status){
	$msg = "";
	switch ($status){
		case "insert": $msg = "Record has been successfully inserted!!!"; break;
		case "update": $msg = "Record has been successfully updated!!!"; break;
		case "delete": $msg = "Record has been successfully deleted!!!"; break;
		/**/
		case "insertError": $msg = "Record has been unsuccessfully inserted!!!"; break;
		case "updateError": $msg = "Record has been unsuccessfully updated!!!"; break;
		case "deleteError": $msg = "Record has been unsuccessfully deleted!!!"; break;
	}
	return $msg;
}
function isChecked($objVal,$tVal,$fVal){
	return $objVal == $tVal ? $tVal : $fVal;
}
function showChecked($objVal,$tVal){
	return $objVal == $tVal ? 'checked' : '';
}

/**
 * 
 * @author thanhnv
 *
 * @param unknown_type $input_time
 * @return unknown
 */
function getMinute($input_time){
	$Hour = date("H",strtotime($input_time));
	$minute = date("i",strtotime($input_time));
	return $Hour * 60 + $minute;
}

/**
 * @author thanhnv
 * @version 1.0.1
 * @25Feb08
 * ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
 * a digit [D] from 1 through 7, beginning with Monday and ending with Sunday.
 * If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. 
 * If 1 January is on a Friday, Saturday or Sunday, it is in week 52 or 53 of the previous year.
*/
function getDayOfWeek($yearWeek){
	$aW = explode('-',$yearWeek);
	$year = $aW[0];
	$week = $aW[1];
	
	$firstDayOfYear = date('N',strtotime($year.'-01-01'));
	
	if(in_array($firstDayOfYear,array(1,2,3,4))) {
		$offset = $firstDayOfYear - 1;
	}else {
		$offset = $firstDayOfYear - 8;
	}
	
	for($i=1;$i<=7;$i++){
		$dateIndex = ($week -1) * 7 -$offset + $i; 
		$aData[$i] = date("Y-m-d",mktime(0,0,0,1,$dateIndex,$year));
	}
	
	return $aData;
}
/**
 * get last year/last month/last week/last day
 *
 * @param unknown_type $input_time
 * @return unknown
 */
function getLastTime($input_time){
	$timestampLastDay = mktime(0,0,0,date("m",strtotime($input_time)),date("d",strtotime($input_time))-1,date("Y",strtotime($input_time)));
	$timestampLastMonth = mktime(0,0,0,date("m",strtotime($input_time))-1,date("d",strtotime($input_time)),date("Y",strtotime($input_time)));
	$timestampLastYear = mktime(0,0,0,date("m",strtotime($input_time)),date("d",strtotime($input_time)),date("Y",strtotime($input_time))-1);
	$timestampLastWeek = mktime(0,0,0,date("m",strtotime($input_time)),date("d",strtotime($input_time))-7,date("Y",strtotime($input_time)));
	
	$aData['lastYear'] = date("Y",$timestampLastYear);
	$aData['lastYearShort'] = date("y",$timestampLastYear);
	$aData['lastMonthShort'] = date("my",$timestampLastMonth);
	$aData['lastMonthFull'] = date("Y-m",$timestampLastMonth);
	$aData['lastDay'] = date("Y-m-d",$timestampLastDay);
	
	$W  = date("W",$timestampLastWeek);
	$currYearOfToday = date("Y",strtotime($input_time));
	$currYearOfLastWeek = date("Y",$timestampLastWeek);
	
	if(in_array($W,array('51','52','53'))){
		$Y = $currYearOfToday == $currYearOfLastWeek ? $currYearOfLastWeek - 1 : $currYearOfLastWeek;
		$aData['lastWeek'] = $Y . "-" .$W;
	}else {
		$aData['lastWeek'] = $currYearOfToday . "-" .$W;
	}
	
	return $aData;
}

function getNumberWeek($input_time){
	$timestamp = strtotime($input_time);
	$Y = intval(date('Y',$timestamp));
	$W = intval(date('W',$timestamp));
	$m = intval(date('m',$timestamp));
	if($m == 12 && $W < 51){
		$Y++;
		return $Y .'-'. $W;
	}elseif ($m==1 && $W >= 51){
		$Y--;
		return $Y .'-'. $W;
	}else{
		return $Y .'-'. $W;
	}
}
/**
 * 
Function Call 						Result 
GET_FORMAT(DATE,'USA') 				'%m.%d.%Y' 
GET_FORMAT(DATE,'JIS') 				'%Y-%m-%d' 
GET_FORMAT(DATE,'ISO') 				'%Y-%m-%d' 
GET_FORMAT(DATE,'EUR') 				'%d.%m.%Y' 
GET_FORMAT(DATE,'INTERNAL') 		'%Y%m%d' 
GET_FORMAT(DATETIME,'USA') 			'%Y-%m-%d %H.%i.%s' 
GET_FORMAT(DATETIME,'JIS') 			'%Y-%m-%d %H:%i:%s' 
GET_FORMAT(DATETIME,'ISO') 			'%Y-%m-%d %H:%i:%s' 
GET_FORMAT(DATETIME,'EUR') 			'%Y-%m-%d %H.%i.%s' 
GET_FORMAT(DATETIME,'INTERNAL') 	'%Y%m%d%H%i%s' 
GET_FORMAT(TIME,'USA') 				'%h:%i:%s %p' 
GET_FORMAT(TIME,'JIS') 				'%H:%i:%s' 
GET_FORMAT(TIME,'ISO') 				'%H:%i:%s' 
GET_FORMAT(TIME,'EUR') 				'%H.%i.%s' 
GET_FORMAT(TIME,'INTERNAL') 		'%H%i%s' 
*/
function Date_DbToScreen($string_date, $format = "m-d-Y"){
	return date($format, strtotime($string_date));
} 
/*nhap du lieu vao database*/
/*EX: 
SELECT STR_TO_DATE('10.31.2003',GET_FORMAT(DATE,'USA'));
-> '2003-10-31'
*/

function Date_ScreenToDb($string_date, $format = "%m-%d-%Y"){
	$rs = mysql_query("SELECT STR_TO_DATE('".$string_date."', '".$format."') AS string_date");
	$row = mysql_fetch_array($rs);
	return $row["string_date"];
}

define('FORMAT_CURRENCY_SYMBOL','&yen;');

function formatPriceCurrency($price){
	return FORMAT_CURRENCY_SYMBOL.number_format($price, 0, '', '');
}

define('FORMAT_CURRENCY_SYMBOL_MINUTE','分');
function formatMinute($min)
{
	return number_format($min, 0, '', '').FORMAT_CURRENCY_SYMBOL_MINUTE;
}

function compareDates($date1,$date2) {
$date1_array = explode("-",$date1);
$date2_array = explode("-",$date2);
$timestamp1 =
mktime(0,0,0,$date1_array[1],$date1_array[2],$date1_array[0]);
$timestamp2 =
mktime(0,0,0,$date2_array[1],$date2_array[2],$date2_array[0]);
if ($timestamp1>$timestamp2) {
return 1;
} else if ($timestamp1<$timestamp2) {
return 2;
} else {
return 0;
}
}


function checkLoginAsAdmin(){
	if(!isset($_SESSION['admin_id']) || $_SESSION['admin_id'] == ''){
		return false;
	}
	return true;
}



function get_month_name($i)
{
	switch ($i){
		case '1':
			return 'Jan';
		case '2':
			return 'Feb';
		case '3':
			return 'Mar';
		case '4':
			return 'Apr';
		case '5':
			return 'May';
		case '6':
			return 'Jun';
		case '7':
			return 'Jul';
		case '8':
			return 'Aug';
		case '9':
			return 'Sep';
		case '10':
			return 'Oct';
		case '11':
			return 'Nov';
		case '12':
			return 'Dec';
		default:
			return 0;
	}
}
/*-- NghiaTT*/

/**
 * MINHHTN 
 */
function displayPhone($phone_num)
{
	if($phone_num!='')
	{
	$first_num=substr($phone_num,0,3);
	$mid_num=substr($phone_num,3,3);
	$last_num=substr($phone_num,6,4);
	
	return "(".$first_num.")"." ".$mid_num."-".$last_num;
	}
	else
	return '';
}

function formatDateToDb($string)
{
	$month=substr($string,0,2);
	$day=substr($string,3,2);
	$year=substr($string,6,4);
	return $year."-".$month."-".$day;
}

function displayDate($string)
{
	$time = strtotime($string);
    return date('m-d-y D h:i A',$time);
}

function displayDate_Dailycash_fee($string)
{
	$time = strtotime($string);
    return date('m-d-y D',$time);
}

function browser_detection( $which_test ) 
{
	// initialize variables
	$browser_name = '';
	$browser_number = '';
	// get userAgent string
	$browser_user_agent = ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) ? strtolower( $_SERVER['HTTP_USER_AGENT'] ) : '';
	//pack browser array
	// values [0]= user agent identifier, lowercase, [1] = dom browser, [2] = shorthand for browser,
	$a_browser_types[] = array('opera', true, 'op' );
	$a_browser_types[] = array('msie', true, 'ie' );
	$a_browser_types[] = array('konqueror', true, 'konq' );
	$a_browser_types[] = array('safari', true, 'saf' );
	$a_browser_types[] = array('gecko', true, 'moz' );
	$a_browser_types[] = array('mozilla/4', false, 'ns4' );
	# this will set a default 'unknown' value
	$a_browser_types[] = array('other', false, 'other' );

	$i_count = count($a_browser_types);
	for ($i = 0; $i < $i_count; $i++)
	{
		$s_browser = $a_browser_types[$i][0];
		$b_dom = $a_browser_types[$i][1];
		$browser_name = $a_browser_types[$i][2];
		// if the string identifier is found in the string
		if (stristr($browser_user_agent, $s_browser)) 
		{
			// we are in this case actually searching for the 'rv' string, not the gecko string
			// this test will fail on Galeon, since it has no rv number. You can change this to 
			// searching for 'gecko' if you want, that will return the release date of the browser
			if ( $browser_name == 'moz' )
			{
				$s_browser = 'rv';
			}
			$browser_number = browser_version( $browser_user_agent, $s_browser );
			break;
		}
	}
	// which variable to return
	if ( $which_test == 'browser' )
	{
		return $browser_name;
	}
	elseif ( $which_test == 'number' )
	{
		# this will be null for default other category, so make sure to test for null
		return $browser_number;
	}

	/* this returns both values, then you only have to call the function once, and get
	 the information from the variable you have put it into when you called the function */
	elseif ( $which_test == 'full' )
	{
		$a_browser_info = array( $browser_name, $browser_number );
		return $a_browser_info;
	}
}

// function returns browser number or gecko rv number
// this function is called by above function, no need to mess with it unless you want to add more features
function browser_version( $browser_user_agent, $search_string )
{
	$string_length = 8;// this is the maximum  length to search for a version number
	//initialize browser number, will return '' if not found
	$browser_number = '';

	// which parameter is calling it determines what is returned
	$start_pos = strpos( $browser_user_agent, $search_string );
	
	// start the substring slice 1 space after the search string
	$start_pos += strlen( $search_string ) + 1;
	
	// slice out the largest piece that is numeric, going down to zero, if zero, function returns ''.
	for ( $i = $string_length; $i > 0 ; $i-- )
	{
		// is numeric makes sure that the whole substring is a number
		if ( is_numeric( substr( $browser_user_agent, $start_pos, $i ) ) )
		{
			$browser_number = substr( $browser_user_agent, $start_pos, $i );
			break;
		}
	}
	return $browser_number;
}

/* created by tienhv
*
* get image
* Date: 17th April 2009
*/
	function show_Picture($pictures_file_name){
			if(!is_file(PATH_UPLOAD_PRODUCT . $pictures_file_name))
				$pictures_file_name = DEFAUL_IMAGE;
					
				$strProductPicture='';	
				if ($pictures_file_name!= DEFAUL_IMAGE) 
						{
						$strProductPicture .= '<a id="thumb1" href="'.URL_UPLOAD_PRODUCT. $pictures_file_name ;
						$strProductPicture .= '" class="highslide" onclick="return hs.expand(this, {captionId: \'highslide_caption\'})" style= "z-index:139211"><img src="';
						$strProductPicture .= URL_UPLOAD_PRODUCT_THUMB_3_2 . $pictures_file_name . '" alt="Highslide JS" class="imgProduct" border =0 style= "z-index:139211" /></a>';
						$strProductPicture .= '<div class=\'highslide-caption\' id="highslide_caption" style= "z-index:139211"></div>';
						}
				else $strProductPicture .= '<img src="'. URL_UPLOAD_PRODUCT . $pictures_file_name . '" alt="Highslide JS" class="imgProduct" border =0 /></a>';
		
			return 	$strProductPicture;		
					}
	function show_Picture_2($pictures_file_name,$pictures_id){
			if(!is_file(PATH_UPLOAD_PRODUCT . $pictures_file_name))
				$pictures_file_name = DEFAUL_IMAGE;
				$strProductPicture='';	
				if ($pictures_file_name!= DEFAUL_IMAGE) 
						{
						$strProductPicture .= '<a id="thumb1" href="#"' ;
						$strProductPicture .= ' class="highslide" onclick="javascript: check_count_image(\''.$pictures_id.'\');" style= "z-index:139211"><img src="';
						$strProductPicture .= URL_UPLOAD_PRODUCT_THUMB . $pictures_file_name . '" alt="Highslide JS" class="imgProduct" border =0 style= "z-index:139211" /></a>';
						$strProductPicture .= '<div class=\'highslide-caption\' id="highslide_caption" style= "z-index:139211"></div>';
						}
				else $strProductPicture .= '<img src="'. URL_UPLOAD_PRODUCT . $pictures_file_name . '" alt="Highslide JS" class="imgProduct" border =0 /></a>';
		
			return 	$strProductPicture;		
					}
function getUserNameLogin()
{
	if( isset($_SESSION['user_name']) && $_SESSION['user_name']!='' )
	{
		return $_SESSION['user_name'];
	}
	else return "";	
}

function getUserIdLogin()
{
	if( isset($_SESSION['user_id']) && $_SESSION['user_id']!='' )
	{
		return $_SESSION['user_id'];
	}
	else return "";	
}

function getUserRole()
{
	return $_SESSION['admin_role'];
}

?>